package com.kedacom.freedomLabel.view.activity;

import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.KeyEvent;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileInputStream;
import com.github.mjdev.libaums.partition.Partition;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.adapter.FunctionAdapter;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.base.UserCache;
import com.kedacom.freedomLabel.databinding.ActivityMainBinding;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Config;
import com.kedacom.freedomLabel.model.bean.Function;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.ConfigDao;
import com.kedacom.freedomLabel.utils.ExcelImportUtils;
import com.kedacom.freedomLabel.utils.IPUtil;
import com.kedacom.freedomLabel.utils.NumFormatUtil;
import com.kedacom.freedomLabel.view.activity.category.NewCategoryControlActivity;
import com.kedacom.freedomLabel.view.activity.item.IDControlActivity;
import com.kedacom.freedomLabel.view.activity.printer.LabelMainActivity;
import com.kedacom.freedomLabel.view.activity.product.ProductControlActivity;
import com.kedacom.freedomLabel.view.activity.report.ReportSummaryActivity;
import com.kedacom.freedomLabel.view.activity.setting.SettingActivity;
import com.kedacom.freedomLabel.viewmodel.MainViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.fast.util.ToastUtil;
import com.kedacom.lego.util.AndroidUtils;
import com.seray.scaleviewlib.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ContentView(R.layout.activity_main)
@ViewModel(MainViewModel.class)
public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {

    private FunctionAdapter mAdapter;
    private List<Function> mData = new ArrayList<>();
    private BroadcastReceiver timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                mBinding.functionBar.timer.setText(NumFormatUtil.getFormatDate());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        importPd = new ProgressDialog(this);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

        register();
        mBinding.functionRecycler.setLayoutManager(new GridLayoutManager(this, 4));
        String appVersionName = AndroidUtils.getVersionName(this);
        int appVersionCode = AndroidUtils.getVersionCode(this);
        mBinding.functionBar.version.setText(String.format("%s.%s", appVersionName, appVersionCode));
        initData();
    }



    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(usbReceiver, filter);
        mBinding.functionBar.companyCode.setText(String.format("%s：%s", getString(R.string.print_company_code), UserCache.companyCode==null?"": UserCache.companyCode));
        String localIpStr = IPUtil.getLocalIpStr(getApplicationContext());
        mBinding.functionAddress.setText(localIpStr);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(usbReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdapter.getData().clear();
        unregisterReceiver(timeReceiver);
    }


    @OnMessage(value = Options.MSG_UPDATE_COLUMN_NAME, always = true)
    public void updateLocalCustomColumnNames() {
        mViewModel.updateLocalCustomColumnNames();
    }

    private void register() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(timeReceiver, timeFilter);
    }



    private void initData() {
        mData.add(new Function(true, "类别管理", R.mipmap.icon_class_manage_200, NewCategoryControlActivity.class));
//        mData.add(new Function(true, "ID管理", R.mipmap.icon_manage_id_200, IDControlActivity.class));
//        mData.add(new Function(true, "产品管理", R.mipmap.icon_product_new_200, ProductControlActivity.class));
//        mData.add(new Function(true, "用户管理", R.mipmap.icon_person_200, OperatorControlActivity.class));
        mData.add(new Function(true, "统计报表", R.mipmap.icon_report_form_200, DataAnalysisActivity.class));
//        mData.add(new Function(true, "打印配置", R.mipmap.icon_print_200, LabelMainActivity.class));
        mData.add(new Function(true, "系统设置", R.mipmap.icon_setting_200, SettingActivity.class));
//        mData.add(new Function(true, "智能称重", R.mipmap.icon_weight_200, ScaleActivity.class));
//        mData.add(new Function(true, "导入导出", R.mipmap.icon_function_daorudaochu_200, ImportDataActivity.class));
//        mData.add(new Function(true, "打印配置", R.mipmap.icon_print_200, LabelMainActivity.class));
        mAdapter = new FunctionAdapter(mData);
        mBinding.functionRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((LegoBaseRecyclerViewAdapter.OnItemClickListener<Function>) (view, function, i) -> {
            beep();
            Class<?> clz = function.getClz();
            if (clz == null) return;
            Intent skipIntent = getSkipIntent(clz);
            switch (i) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
            }
//            if(i==7){
//                finish();
//                return;
//            }
            startActivity(skipIntent);
        });
    }

    private ProgressDialog importPd;
    private UsbManager mUsbManager;
    private UsbMassStorageDevice[] storageDevices;
    private static final String ACTION_USB_PERMISSION = "com.infol.density.USB_PERMISSION";
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    PendingIntent pendingIntent;

    private void importData() {

        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        if (storageDevices.length <= 0) {
            ToastUtils.showShort("没有发现usb存储设备");
            return;
        }

        if (!checkPerssion(storageDevices[0])) {  //检查是否有权限
            mUsbManager.requestPermission(storageDevices[0].getUsbDevice(), pendingIntent);
            return;
        }

        importPd.setTitle("数据导入中，请稍后...");
        importPd.setCancelable(false);
        importPd.setCanceledOnTouchOutside(false);
        importPd.show();

        AppExecutors.getInstance().insertIO()
                .submit(() -> {
                    try {
                        UsbFile root = readDevice(storageDevices[0]).getRootDirectory();
                        if (root == null) return;
                        UsbFile choiceFile = null;
                        for (UsbFile file : root.listFiles()) {
                            if ("数据导入.xls".equals(file.getName())) {
                                choiceFile = file;
                                break;
                            }
                        }
                        if (choiceFile == null) {
                            ToastUtil.showDefaultToast("未找到数据导入文件。");
                            return;
                        }
                        List<Category> categories = ExcelImportUtils.readCategories(new UsbFileInputStream(choiceFile));
                        List<List<List<Item>>> items = ExcelImportUtils.readItemList(new UsbFileInputStream(choiceFile), categories);
/*                        File choiceFile = new File(Environment.getExternalStorageDirectory(), "数据导入.xls");
                        if (!choiceFile.exists()) {
                            ToastUtil.showDefaultToast("未找到数据导入文件。");
                            return;
                        }

                        List<Category> categories = ExcelImportUtils.readCategories(choiceFile);
                        List<List<List<Item>>> items = ExcelImportUtils.readItemList(choiceFile, categories);*/

                        AppDatabase.getInstance().runInTransaction(() -> {
                            try {
                                // 清空categories数据
                                AppDatabase.getInstance().categoryDao().delete();
                                //清空item数据
                                AppDatabase.getInstance().itemDao().delete();
                                //创建categories数据
                                AppDatabase.getInstance().categoryDao().save(categories);
                                // 创建Item数据
                                for (int i = 0; i < items.size(); i++) {
                                    List<List<Item>> temp = items.get(i);
                                    Category category = categories.get(i);

                                    for (List<Item> itemList : temp) {
                                        for (Item item : itemList) {
//                                            item.parent = category.uuid;
                                        }
                                        AppDatabase.getInstance().itemDao().save(itemList);
                                    }
                                }
                                importSuccess();
                            } catch (Exception e) {
                                importFail("导入失败，请检查数据的合法性。");
                                throw e;
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        importFail("导出失败，请重新拔插usb设备。");
                    }

                });
    }

    private void importFail(String msg) {
        runOnUiThread(() -> {
            if (importPd != null && importPd.isShowing())
                importPd.dismiss();
            ToastUtils.showLong(msg);
        });
    }

    private void importSuccess() {
        runOnUiThread(() -> {
            if (importPd != null && importPd.isShowing())
                importPd.dismiss();
            ToastUtils.showLong("导入成功");
        });
    }

    /**
     * 根据设备获取路径
     *
     * @param device
     * @return
     */


    public FileSystem readDevice(UsbMassStorageDevice device) {
        try {

            if (!checkPerssion(device)) {  //检查是否有权限
                mUsbManager.requestPermission(device.getUsbDevice(), pendingIntent);
                return null;
            }

            device.init();//使用设备之前需要进行 初始化
            Partition partition = device.getPartitions().get(0); //仅使用设备的第一个分区
            FileSystem currentFs = partition.getFileSystem();
            // currentFs.getCapacity(); //容量大小
            // currentFs.getOccupiedSpace(); //已使用大小
            // currentFs.getFreeSpace();  //未使用的大小
            UsbFile root = currentFs.getRootDirectory();//获取根目录
            String deviceName = currentFs.getVolumeLabel();//获取设备标签
            return currentFs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检查usb设备的权限
     *
     * @param device
     * @return
     */
    public boolean checkPerssion(UsbMassStorageDevice device) {
        if (mUsbManager == null) {
            return false;
        }
        if (mUsbManager.hasPermission(device.getUsbDevice())) {//有就直接读取设备是否有权限
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        switch (keyCode) {
            case KeyEvent.KEYCODE_F3:
                shutDown();
                return true;
            case KeyEvent.KEYCODE_BACK:
                finish();
                return true;
            case KeyEvent.KEYCODE_A:
                mMisc.beep();
                shutDown();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 关机操作
     */
    public void shutDown() {
        Intent shutDownIntent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
        shutDownIntent.putExtra("android.intent.extra.KEY_CONFIRM", true);
        shutDownIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(shutDownIntent);
    }




    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            importData();
                        }
                    } else {
                        Log.d("res", "permission denied for device " + device);
                    }
                }
            }
        }
    };
}